const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { validatePagination } = require('../utils/validation');

// 获取字体边框列表
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      search 
    } = req.query;
    
    // 验证分页参数
    const { error } = validatePagination({ page: parseInt(page), pageSize: parseInt(pageSize) });
    if (error) {
      return res.status(400).json({ error: error.details[0].message });
    }
    
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);
    
    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];
    
    if (search) {
      whereClause += ' AND fb.name LIKE ?';
      params.push(`%${search}%`);
    }
    
    // 查询总数
    const [countResult] = await db.execute(
      `SELECT COUNT(*) as total FROM font_borders fb ${whereClause}`,
      params
    );
    const total = countResult[0].total;
    
    // 查询数据
    const query = `
      SELECT 
        fb.id,
        fb.name,
        fb.border_style,
        fb.border_width,
        fb.border_color,
        fb.preview,
        fb.created_at,
        fb.updated_at
      FROM font_borders fb
      ${whereClause}
      ORDER BY fb.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await db.execute(query, [...params, limit, offset]);
    
    // 格式化数据
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        border_style: row.border_style,
        border_width: row.border_width,
        border_color: row.border_color,
        preview: row.preview,
        createdAt: row.created_at,
        updatedAt: row.updated_at
      }
    }));
    
    res.json({
      data,
      meta: {
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          pageCount: Math.ceil(total / parseInt(pageSize)),
          total
        }
      }
    });
  } catch (error) {
    console.error('获取字体边框列表失败:', error);
    res.status(500).json({ error: '获取字体边框列表失败' });
  }
});

module.exports = router;